package com.yskj.czy.testandfix;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends Activity {
    private Button bt;
    private Button bt_tv;
    private float percent = 0;
    private static final String APATCH_PATH = "/fix.apatch"; // 补丁文件名
    private String url = "http://os4p3lhbo.bkt.clouddn.com/fix.apatch";
    private StorageManager mStorageManager;
    private int REQUEST_CODE_GRAINT_URI = 1;
    final int TAG_PHOTO_CAMERA=200;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
         private static String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = (Button) findViewById(R.id.bt);
        bt_tv = (Button) findViewById(R.id.bt_tv);
        bt_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showToast();
            }
        });
        new Thread(new DownloadFileThread()).start();
    }
    private void showToast() {
        Toast.makeText(this, "打补丁之前", Toast.LENGTH_LONG).show();
    }

    /**
     * 网络请求下载补丁包
     */
    private class DownloadFileThread implements Runnable {
        @Override
        public void run() {
            try {
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + APATCH_PATH);
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Accept-Encoding", "identity");
                long sum = 0;
                if (file.exists()) {
                    file.delete();
                        /*sum = file.length();
                        // 设置断点续传的开始位置
                        connection.setRequestProperty("Range", "bytes=" + file.length() + "-");*/
                }
                int code = connection.getResponseCode();
                if (code == 200 || code == 206) {
                    int contentLength = connection.getContentLength();
                    contentLength += sum;
                    InputStream is = connection.getInputStream();
                /*
                *
                * 创建一个向具有指定 name 的文件中写入数据的输出文件流。
                * true表示当文件在下载过程中出现中断，
                * 当再次链接网络时，将会从断点处追加。
                *
                * */
                    if(Build.VERSION.SDK_INT>=23){
                        verifyStoragePermissions(MainActivity.this);
                    }
                    FileOutputStream fos = new FileOutputStream(file, true);
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, length);
                        sum += length;
                        percent = sum * 100.0f / contentLength;
                    }
                    update();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void update() {
        String patchFileStr =Environment.getExternalStorageDirectory().getAbsolutePath() + APATCH_PATH;
        try {
            AndFixApplication.mPatchManager.addPatch(patchFileStr);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static void verifyStoragePermissions(Activity activity) {
                 // Check if we have write permission
                 int permission = ActivityCompat.checkSelfPermission(activity,
                               Manifest.permission.WRITE_EXTERNAL_STORAGE);

                if (permission != PackageManager.PERMISSION_GRANTED) {
                         // We don't have permission so prompt the user
                         ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                                         REQUEST_EXTERNAL_STORAGE);
                     }
            }
}
